package com.browsesoft.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/*
 * 流的工具类
 */
public class StreamHelper {

	/*
	 * 在流中读取字符串，注意汉字处理，如果读到的二进制串的最后一个字节大于0x80，
	 * 说明是汉字的半个字节，这时，要往前找，看是否一半汉字，如果是，把这一半汉字 留到下一次读取
	 */
	public static String getString(InputStream is) throws IOException {
		StringBuffer strb = new StringBuffer();
		byte[] buffer = new byte[1024];
		try {
			// 读到的实际长度
			int length = is.read(buffer);
			while (length != -1) {
				if (isHalf(buffer, length)) {
					strb.append(new String(buffer, 0, length - 1));
					buffer[0] = buffer[length - 1];
					length = is.read(buffer, 1, 1023) + 1;
				} else {
					strb.append(new String(buffer, 0, length));
					length = is.read(buffer);
				}
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return strb.toString();
	}

	private static boolean isHalf(byte[] buffer, int len) {
		if (buffer[len - 1] >= 0) {
			return false;
		}
		int num = 1;
		for (int i = len - 2; i >= 0 && buffer[i] < 0; i--) {
			num++;
		}
		return num % 2 == 1;
	}

	/*
	 * 把输入流的内容读到输出流中
	 */
	public static void transformStream(InputStream is, OutputStream os) {
		try {
	          String s = "";
	          s.substring(s.lastIndexOf("\\"),s.length());
			byte[] buffer = new byte[1024];
			// 读取的实际长度
			int length = is.read(buffer);
			while (length != -1) {
				os.write(buffer, 0, length);
				length = is.read(buffer);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/*
	 * 得到输入流的长度
	 */
	


}
